<?php

use Illuminate\Database\Capsule\Manager as DB;
use SliderCapcha\SliderCapcha;
use EasyWeChat\Factory;
use Payment\Notify;

class PublicController extends CoreController
{
    public function infoAction()
    {
        $row = DB::table('sys_config')->where('type', 1)->pluck('value', 'key');
        json(['ret' => 0, 'msg' => '系统信息', 'data' => $row]);
    }

    public function makeAction()
    {
        (new Captcha())->make();
    }

    public function adminmakeAction()
    {
        $config['dir'] = APP_PATH . '/public/plugins/slide-capcha/bg/';
        $sc            = new SliderCapcha($config);
        $sc->make();
    }

    public function loginAction()
    {
        do {
            if (!Captcha::check($this->get('yzcode'))) {
                $result = [
                    'ret' => 1,
                    'msg' => '图片验证失败.',
                ];
                break;
            }
            $username = $this->get('username', '');
            $password = $this->get('password', '');
            $inputs   = [
                'username' => ['value' => $username, 'role' => 'required|exists:members.phone', 'msg' => '手机号'],
                'password' => ['value' => $password, 'role' => 'required', 'msg' => '密码'],
            ];
            $ret      = Validate::check($inputs);
            if (!empty($ret)) {
                $result = [
                    'ret' => 2,
                    'msg' => $ret,
                ];
                break;
            }
            $sysusers = new membersModel();
            if ($sysusers->checkUsername($username) == FALSE) {
                $result = [
                    'ret' => 3,
                    'msg' => '无此账号.',
                ];
                break;
            }
            if ($sysusers->checkStatus($username) == FALSE) {
                $result = [
                    'ret' => 4,
                    'msg' => '账号已锁定.',
                ];
                break;
            }
            if ($sysusers->checkPassword($username, $password) == FALSE) {
                if (!isset($this->session->try_times)) {
                    $this->session->try_times = 0;
                }
                $this->session->try_times++;
                if ($this->session->try_times > 5) {
                    $result = [
                        'ret' => 4,
                        'msg' => '账号已锁定.',
                    ];
                    $rows   = [
                        'lockuntil' => time() + 60 * 20,
                    ];
                    DB::table('members')->where('username', '=', $username)->update($rows);
                    setcookie('lockFlag', 1, time() + 60 * 20);
                    $this->session->del('try_times');
                } else {
                    $result = [
                        'ret' => 5,
                        'msg' => '密码有误,剩余' . (5 - $this->session->try_times) . '次',
                    ];
                }
                break;
            }
            //if ($data = $sysusers->setUserLogin($username, $password, $module)) {
            if ($data = $sysusers->setUserLogin($username, $password)) {
                $this->session->del('try_times');
                $result = [
                    'ret'  => 0,
                    'msg'  => '登陆成功.',
                    'data' => $data
                ];
            } else {
                $result = [
                    'ret' => 6,
                    'msg' => '登陆失败.',
                ];
            }
        } while (FALSE);

        json($result);
    }

    public function corpLoginAction()
    {
        do {
            if (!Captcha::check($this->get('yzcode'))) {
                $result = [
                    'ret' => 1,
                    'msg' => '图片验证失败.',
                ];
                break;
            }
            $inputs = [
                'username' => $this->get('username'),
                'password' => $this->get('password')
            ];
            $roles  = [
                'username' => ['role' => 'required|exists:members.phone', 'msg' => '账号'],
                'password' => ['role' => 'required', 'msg' => '密码'],
            ];
            Validate::check($inputs, $roles);
            $sysusers = new membersModel();
            if ($sysusers->checkUsername($inputs['username']) == FALSE) {
                $result = [
                    'ret' => 3,
                    'msg' => '无此账号.',
                ];
                break;
            }
            if ($sysusers->checkStatus($inputs['username']) == FALSE) {
                $result = [
                    'ret' => 4,
                    'msg' => '账号已锁定.',
                ];
                break;
            }
            if ($sysusers->checkPassword($inputs['username'], $inputs['password']) == FALSE) {
                if (!isset($this->session->try_times)) {
                    $this->session->try_times = 0;
                }
                $this->session->try_times++;
                if ($this->session->try_times > 5) {
                    $result = [
                        'ret' => 4,
                        'msg' => '账号已锁定.',
                    ];
                    DB::table('admin')->where('username', $inputs['username'])->update(['lockuntil' => time() + 60 * 20]);
                    setcookie('lockFlag', 1, time() + 60 * 20);
                    $this->session->del('try_times');
                } else {
                    $result = [
                        'ret' => 5,
                        'msg' => '密码有误,剩余' . (5 - $this->session->try_times) . '次',
                    ];
                }
                break;
            }
            if ($data = $sysusers->setUserLogin($inputs['username'], $inputs['password'])) {
                $this->session->del('try_times');
                $result = [
                    'ret'  => 0,
                    'msg'  => '登陆成功.',
                    'data' => $data
                ];
            } else {
                $result = [
                    'ret' => 6,
                    'msg' => '登陆失败.',
                ];
            }
        } while (FALSE);
        json($result);
    }

    public function adminloginAction()
    {
        if (!$this->isPost()) {
            $this->_view->assign('title', DB::table('sys_config')->where('key', 'name')->value('value'));
            $this->_view->display('public/adminlogin.html');
        } else {
            do {
                if (!SliderCapcha::check()) {
                    $result = [
                        'ret' => 1,
                        'msg' => '滑动验证失败.',
                    ];
                    break;
                }
                $inputs = $this->postData;
                $roles  = [
                    'username' => ['role' => 'required|exists:admin.username', 'msg' => '用户名'],
                    'password' => ['role' => 'required', 'msg' => '密码'],
                ];
                Validate::check($inputs, $roles);
                $sysusers = new adminModel();
                if ($sysusers->checkUsername($inputs['username']) == FALSE) {
                    $result = [
                        'ret' => 3,
                        'msg' => '无此账号.',
                    ];
                    break;
                }
                if ($sysusers->checkStatus($inputs['username']) == FALSE) {
                    $result = [
                        'ret' => 4,
                        'msg' => '账号已锁定.',
                    ];
                    break;
                }
                if ($sysusers->checkPassword($inputs['username'], $inputs['password']) == FALSE) {
                    if (!isset($this->session->try_times)) {
                        $this->session->try_times = 0;
                    }
                    $this->session->try_times++;
                    if ($this->session->try_times > 5) {
                        $result = [
                            'ret' => 4,
                            'msg' => '账号已锁定.',
                        ];
                        $rows   = [
                            'lockuntil' => time() + 60 * 20,
                        ];
                        DB::table('admin')->where('username', '=', $inputs['username'])->update($rows);
                        setcookie('lockFlag', 1, time() + 60 * 20);
                        $this->session->del('try_times');
                    } else {
                        $result = [
                            'ret' => 5,
                            'msg' => '密码有误,剩余' . (5 - $this->session->try_times) . '次',
                        ];
                    }
                    break;
                }
                if ($data = $sysusers->setUserLogin($inputs['username'], $inputs['password'])) {
                    $this->session->del('try_times');
                    $result = [
                        'ret'  => 0,
                        'msg'  => '登陆成功.',
                        'data' => $data
                    ];
                } else {
                    $result = [
                        'ret' => 6,
                        'msg' => '登陆失败.',
                    ];
                }
            } while (FALSE);
            json($result);
        }
    }

    public function wxMiniProGetUserInfoAction()
    {
        $config        = [
            'app_id'        => DB::table('sys_config')->where('type', 3)->where('key', 'appid')->value('value'),
            'secret'        => DB::table('sys_config')->where('type', 3)->where('key', 'secret')->value('value'),
            'response_type' => 'array',
        ];
        $encryptedData = $this->input('encryptedData');
        $iv            = $this->input('iv');
        $code          = $this->input('js_code');
        try {
            $app         = Factory::miniProgram($config);
            $oauth       = $app->auth->session($code);
            $openid      = $oauth['openid'];
            $session_key = $oauth['session_key'] ?? '';
            if (isset($oauth['unionid'])) {
                $unionid = $oauth['unionid'];
                $user    = DB::table("customer")->where('unionid', $unionid)->first();
                if ($user) {
                    DB::table("customer")->where("id", $user->id)->update(['wxpro_openid' => $openid, 'wx_sessionkey' => $session_key]);
                    $info = (new customerModel)->setWxproUnionidLogin($unionid);
                    ret(0, '登陆成功', $info);
                } else {
                    $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
                    $rows          = [
                        'username'      => $decryptedData['nickName'],
                        'gender'        => $decryptedData['gender'],
                        'avatar'        => $decryptedData['avatarUrl'],
                        'wxpro_openid'  => $decryptedData['openId'],
                        'wx_unionid'    => $decryptedData['unionId'] ?? '',
                        'wx_sessionkey' => $session_key,
                        'created_at'    => date('Y-m-d H:i:s'),
                    ];
                    DB::table('customer')->insert($rows);
                    $info = (new customerModel)->setWxproUnionidLogin($unionid);
                    ret(0, '登陆成功', $info);
                }
            } else {
                $user = DB::table("customer")->where('wxpro_openid', $openid)->first();
                if ($user) {
                    DB::table("customer")->where("id", $user->id)->update(['wx_sessionkey' => $session_key]);
                    $info = (new customerModel)->setWxproOpenidLogin($openid);
                    ret(0, '登陆成功', $info);
                } else {
                    $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
                    $rows          = [
                        'username'      => $decryptedData['nickName'],
                        'gender'        => $decryptedData['gender'],
                        'avatar'        => $decryptedData['avatarUrl'],
                        'wxpro_openid'  => $decryptedData['openId'],
                        'wx_unionid'    => $decryptedData['unionId'] ?? '',
                        'wx_sessionkey' => $session_key,
                        'created_at'    => date('Y-m-d H:i:s'),
                    ];
                    DB::table('customer')->insert($rows);
                    $info = (new customerModel)->setWxproOpenidLogin($openid);
                    ret(0, '登陆成功', $info);
                }
            }
        } catch (Exception $e) {
            ret(1, '获取用户信息失败', $e->getMessage());
        }
    }

    #微信支付回调
    public function wxNotifyAction()
    {
        #\Log::out('notify', 'I', file_get_contents("php://input"));
        $wxConfig = DB::table('sys_config')->where('type', 3)->pluck('value', 'key');
        Notify::run('NotifyWx', $wxConfig, ['ordersModel', 'notifyProcess']);
    }

    /**
     * @name 生成二维码
     */
    public function qrcodeAction()
    {
        $data = $this->get('data');
        QRcode::png($data);
    }

    public function clearGoodsContentAction()
    {
        set_time_limit(0);
        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $no = '010';
        $times = 0;
        DB::table('corp'.$no.'_goods_content')->where('content', 'like', '%所属分类：<a%')
            ->chunkById(100, function ($rows) use($no, &$times) {
                foreach ($rows as $row) {
                    $content = substr($row->content, 0, strpos($row->content, '所属分类：<a'));
                    DB::table('corp'.$no.'_goods_content')
                        ->where('id', $row->id)
                        ->update(['content' => $content]);
                }
                echo (++$times) . '  ';
        });
        echo 'Done';
    }


}
